/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.common;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SentinelThreadPool implements Executor {
  private static Logger logger = LoggerFactory.getLogger(SentinelThreadPool.class);

  public static class TaskGroup { 
    private int nSubmittedTask = 0;
    private Runnable sentinel = null;

    synchronized private Runnable wrap(final Runnable task) {
      assert sentinel == null: "Sentinel already has been submitted.";

      nSubmittedTask++;
      Runnable r = new Runnable() {
        @Override 
        public void run() {
          try {
            task.run();
          } finally {
            Runnable s = onEnd();
            if (s != null) {
              s.run();
            }
          }
        }
      };
      return r;
    }

    synchronized private Runnable wrapSentinel(Runnable task) {
      assert sentinel == null: "Sentinel already has been submitted.";

      sentinel = task;
      nSubmittedTask++;
      Runnable r = new Runnable() {
        @Override 
        public void run() {
          Runnable s = onEnd();
          if (s != null) {
            s.run();
          }
        }
      };

      return r;
    }

    synchronized private Runnable onEnd() {
      assert nSubmittedTask > 0;
      nSubmittedTask--;
      return (nSubmittedTask == 0)?sentinel:null;
    }
  }

  private ExecutorService threadPool;

  public SentinelThreadPool(int corePoolSize,
                            int maximumPoolSize,
                            long keepAliveTime,
                            TimeUnit unit,
                            BlockingQueue<Runnable> workQueue,
                            ThreadFactory threadFactory,
                            RejectedExecutionHandler handler) {
    this.threadPool = new ThreadPoolExecutor(
        corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
        threadFactory, handler);
  }

  public void shutdown() {
    threadPool.shutdown();
  }

  public <T> Future<T> submit(Callable<T> task) {
    logger.debug("submit called.");
    return threadPool.submit(task);
  }

  @Override
  public void execute(Runnable command) {
    threadPool.execute(command);
  }

  public void execute(TaskGroup taskGroup, Runnable command) {
    execute(taskGroup.wrap(command));
  }

  public void executeSentinel(TaskGroup taskGroup, Runnable command) {
    execute(taskGroup.wrapSentinel(command));
  }
}
